package wubj.com.floatwindow;

import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import wubj.com.floatwindow.utils.LogUtil;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
public class FloatWindowService extends Service {

    private static final String TAG = FloatWindowService.class.getSimpleName();

    private Handler handler = new Handler();
    private Timer timer;
    private List<String> names;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.d(TAG, "wubaojie>>>onStartCommand: 服务开启");
        names = getHomes();
        // 开启定时器，每隔0.5秒刷新一次
        if (timer == null) {
            timer = new Timer();
            timer.scheduleAtFixedRate(new RefreshTask(), 0, 1000);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Service被终止的同时也停止定时器继续运行
        timer.cancel();
        timer = null;
    }

    private class RefreshTask extends TimerTask {

        @Override
        public void run() {
            // 当前界面是桌面
            if (isHome()) {
                //没有悬浮窗显示，则创建悬浮窗
                if (!MyWindowManager.isWindowShowing()) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.d(TAG, "wubaojie>>>run: 创建小窗口");
                            MyWindowManager.createSmallWindow(getApplicationContext());
                        }
                    });
                }
            } else {
                //有悬浮窗显示，则移除悬浮窗
                if (MyWindowManager.isWindowShowing()) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.d(TAG, "wubaojie>>>run: 移除小窗口");
                            MyWindowManager.removeSmallWindow(getApplicationContext());
                            LogUtil.d(TAG, "wubaojie>>>run: 移除大窗口");
                            MyWindowManager.removeBigWindow(getApplicationContext());
                        }
                    });
                }
            }

//            // 当前界面是桌面,没有悬浮窗显示，则创建悬浮窗
//            if (isHome() && !MyWindowManager.isWindowShowing()) {
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        LogUtil.d(TAG, "wubaojie>>>run: 创建小窗口");
//                        MyWindowManager.createSmallWindow(getApplicationContext());
//                    }
//                });
//            }
//            //当前界面不是桌面,有悬浮窗显示，则移除悬浮窗
//            else if (!isHome() && MyWindowManager.isWindowShowing()) {
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        LogUtil.d(TAG, "wubaojie>>>run: 移除小窗口");
//                        MyWindowManager.removeSmallWindow(getApplicationContext());
//                        LogUtil.d(TAG, "wubaojie>>>run: 移除大窗口");
//                        MyWindowManager.removeBigWindow(getApplicationContext());
//                    }
//                });
//            }
            // 当前界面是桌面，且有悬浮窗显示，则更新内存数据。
//            else if (isHome() && MyWindowManager.isWindowShowing()) {
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        LogUtil.d(TAG, "wubaojie>>>run: 更新界面");
//                        MyWindowManager.updateUsedPercent(getApplicationContext());
//                    }
//                });
//            }
        }
    }

    private String topName = "";

    /**
     * 判断当前界面是否是桌面
     */
    private boolean isHome() {
//        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//        String topName = ""; /* Android5.0之后获取程序锁的方式是不一样的*/
//        if (Build.VERSION.SDK_INT > 20) {// 5.0及其以后的版本
//            List<ActivityManager.RunningAppProcessInfo> tasks = mActivityManager.getRunningAppProcesses();
//            if (null != tasks && tasks.size() > 0) {
//                topName = tasks.get(0).processName;
//            }
//
////            List<ActivityManager.AppTask> tasks = mActivityManager.getAppTasks();
////            if (null != tasks && tasks.size() > 0) {
////                for (ActivityManager.AppTask task : tasks) {
////                    topName = task.getTaskInfo().baseIntent.getComponent().getPackageName();
////                    LogUtil.d(TAG, "wubaojie>>>isHome: packageName:" + topName);
////                }
////            }
//        } else {
//            List<ActivityManager.RunningTaskInfo> rTasks = mActivityManager.getRunningTasks(1);
//            ActivityManager.RunningTaskInfo task = rTasks.get(0);
//            topName = task.topActivity.getPackageName();
//        }
//        topName = getTopActivityFromLollipopOnwards();
        String tempTopName = getRunningApp();
        if (tempTopName != null) {
            topName = tempTopName;
        }
        LogUtil.d(TAG, "wubaojie>>>isHome: topName:" + topName);
        return names.contains(topName);
    }

    /**
     * 获得属于桌面的应用的应用包名称
     *
     * @return 返回包含所有包名的字符串列表
     */
    private List<String> getHomes() {
        names = new ArrayList<>();
        PackageManager packageManager = this.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo ri : resolveInfo) {
            names.add(ri.activityInfo.packageName);
        }
        LogUtil.d(TAG, "wubaojie>>>getHomes: " + names + " size:" + names.size());
        return names;
    }

    public String getTopActivityFromLollipopOnwards() {
        String topPackageName = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
            long time = System.currentTimeMillis();
            // We get usage stats for the last 10 seconds
            List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 2000, time);
            // Sort the stats by the last time used
            if (stats != null) {
                SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
                for (UsageStats usageStats : stats) {
                    mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                }
                if (!mySortedMap.isEmpty()) {
                    topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                    Log.e("TopPackage Name", topPackageName);
                }
            }
        }
        return topPackageName;
    }

    private String getRunningApp() {
        UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
        long ts = System.currentTimeMillis();
        List<UsageStats> queryUsageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts - 2000, ts);
        if (queryUsageStats == null || queryUsageStats.isEmpty()) {
            return null;
        }

        UsageStats recentStats = null;
        for (UsageStats usageStats : queryUsageStats) {
            if (recentStats == null || recentStats.getLastTimeUsed() < usageStats.getLastTimeUsed()) {
                recentStats = usageStats;
            }
        }
        return recentStats != null ? recentStats.getPackageName() : null;

    }
}